import type { FC } from 'react'
import { useCallback, useEffect, useRef } from 'react'
import { useAsyncValue, useBlocker, useBeforeUnload } from 'react-router-dom'
import { stepsItem } from '@/views/article/article-add'
import { Steps, Modal } from 'antd'
import useArtEditStore, { selectCurrent } from '@/store/art-edit-store'
import { ArticleSteps } from '@/store/art-add-store'
import EditBase from './art-base'
import EditCover from './art-cover'
import EditContent from './art-content'
import EditResult from './art-result'

const ArtEdit: FC = () => {
  const asyncValue = useAsyncValue() as [BaseResponse<CateItem[]>]
  const current = useArtEditStore(selectCurrent)
  const modalRef = useRef<ReturnType<typeof Modal.confirm> | null>()

  const blocker = useBlocker(({ currentLocation, nextLocation }) => {
    return currentLocation.pathname !== nextLocation.pathname && current !== ArticleSteps.done
  })

  useEffect(() => {
    if (blocker.state === 'blocked') {
      if (modalRef.current) {
        return
      }
      modalRef.current = Modal.confirm({
        title: '温馨提示',
        content: '您所做的更改将会丢失，是否确认离开当前页面？',
        onOk() {
          blocker.proceed()
          // resetCurrent()
        },
        onCancel() {
          blocker.reset()
          modalRef.current = null
        }
      })
    }
  }, [blocker])

  useBeforeUnload(
    useCallback((e) => {
      e.preventDefault()
    }, [])
  )

  return (
    <>
      <Steps size="small" current={current} items={stepsItem} />

      <div style={{ marginTop: 20 }}>
        {/* 步骤条对应的组件 */}
        {current === ArticleSteps.base && <EditBase cates={asyncValue[0].data || []} />}
        {current === ArticleSteps.cover && <EditCover />}
        {current === ArticleSteps.content && <EditContent />}
        {current === ArticleSteps.done && <EditResult />}
      </div>
    </>
  )
}

export default ArtEdit
